import React, { Component, Suspense } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Icon, Tooltip, Form, Input, Tree, Button, message, Modal, Spin, Select, TreeSelect } from "antd";
import styles from "./index.less";
import UserSession from "@/UserSession";
import { knowledgeQaCategoryTree } from '@/services/knowledgemanagement';
const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const TreeNodes = TreeSelect.TreeNode;
const { confirm } = Modal;
import icon1 from "@/assets/overview/1.png";
import icon2 from "@/assets/overview/2.png";
import icon4 from "@/assets/overview/4.png";
import icon6 from "@/assets/overview/6.png";
import icon7 from "@/assets/overview/7.png";
import chu from "@/assets/overview/chu.png";
import jin from "@/assets/overview/jin.png";
import ReferenceTemplate from './referenceTemplate';

class LeftTree extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataTree: [],
			iconJudge: true,
			defaultExpandAll: true,
			selectedKeys: null,
			path: "", // 父节点名称
			parentPath: "",
			disabled: null,
			disablex: null,
			showModel: false,
			cid: null,
			title: "",
			loading: false,
			moveShow: false,
			value: undefined,
			parentPathMove: "",
			targetRobotId: "",
			open: [],
			openB: [],
			dataTreeB: [],
			selectedKeysB: null,
			pathB: "",
			parentPathB: "",
			cidB: null,
			titleB: "",
			targetRobotIdB: "",
			buttonDJ: false,
			buttonNonew: false,
			qaListCz: "",
			isShared: false,
			parentId: "",
			expandedKeys: [],
			autoExpandParent: true,
			rootNode: "",
		};
	}

	componentWillReceiveProps(nextProps, nextContext) {
		if (this.props.onRef) {
			this.props.onRef(this);
		};
		if (nextProps.qaListCz !== this.state.qaListCz) {
			this.setState({ qaListCz: nextProps.qaListCz });
		}
	}

	fetch = (flag) => {
		this.setState({ loading: true });
		const { dispatch, currentUser, categoryId } = this.props;
		console.log(this.props);
		this.reqRef = requestAnimationFrame(async () => {
			if (!UserSession.isAdmin() && UserSession.isSystemKnowledge()) {
				let res = await knowledgeQaCategoryTree({ rootCategoryId: categoryId });
				if (res && res[0]) {
					if (flag === 100) {
						this.setState({ dataTree: res, loading: false });
					} else {
						// 判断展开收起状态
						const childrenIds = [res[0].id];
						this.localStorageKeys(childrenIds);
						// 判断节点选中状态 传入所有分类的节点信息，如果没有储存的节点，则选中所有分类节点
						let obj = {
							cid: res[0].id,
							title: res[0].name,
							parentId: res[0].parentId,
							parentPath: res[0].parentPath,
						};
						this.localStorageCurrentNode(obj);
						// 记录所有分类的id，用于当默认选中所有分类时，判断分类的操作按钮
						this.setState({ dataTree: res, loading: false, rootNode: res[0].id });
					}
				};
				this.setState({ loading: false });
			} else {
				dispatch({
					type: "leftTree/fetch",
					payload: { categoryId },
					callback: (res) => {
						if (res && res[0]) {
							if (flag === 100) {
								this.setState({ dataTree: res, loading: false });
							} else {
								// 判断展开收起状态
								const childrenIds = [res[0].id];
								this.localStorageKeys(childrenIds);
								// 判断节点选中状态 传入所有分类的节点信息，如果没有储存的节点，则选中所有分类节点
								let obj = {
									cid: res[0].id,
									title: res[0].name,
									parentId: res[0].parentId,
									parentPath: res[0].parentPath,
								};
								this.localStorageCurrentNode(obj);
								// 记录所有分类的id，用于当默认选中所有分类时，判断分类的操作按钮
								this.setState({ dataTree: res, loading: false, rootNode: res[0].id });
							}
						};
						this.setState({ loading: false });
					},
				});
			}
		});
	};

	/**
	 * 处理记忆展开收起状态
	 * @param keys
	 */
	localStorageKeys = (keys) => {
		// 先判断有没有储存的展开收起 如果没有则展开所有分类节点，如果有，则展开储存的节点
		const treeExpandedKeys = window.localStorage.getItem("treeExpandedKeys");
		if (treeExpandedKeys) {
			this.setState({ expandedKeys: treeExpandedKeys.split(",") });
		} else {
			window.localStorage.setItem("treeExpandedKeys", keys);
			this.setState({ expandedKeys: keys });
		}
	};

	/**
	 * 处理记忆选中节点
	 */
	localStorageCurrentNode = (obj) => {
		// 先判断有没有储存的选中节点 如果没有则选中所有分类节点，如果有，则选中储存的节点
		// const currentNode = window.localStorage.getItem("currentNode");
		// let newNode = null;
		// if (currentNode) {
		// 	newNode = JSON.parse(currentNode);
		// } else {
		// 	window.localStorage.setItem("currentNode", JSON.stringify(obj));
		// 	newNode = obj;
		// };
		const { cid, parentId, parentPath, title } = obj;
		this.setState({ cid, parentId, title, parentPath, selectedKeys: cid, });
		// 控制右侧展示知识点

		this.props.getListByTreeRoot({ id: obj.cid, parentPath: obj.path, parentId: obj.parentId, title: obj.title, });
	};

	componentWillMount() {
		this.setState({ loading: true });
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this)
		}
	}

	openedTreeNodes(data) {
		return data.map((item) => {
			let a = this.state.open;
			if (item.children) {
				if (item.data.opened) {
					a.push(item.id);
				};
				this.openedTreeNodes(item.children);
			};
			this.setState({ open: a });
		});
	}

	onSelect = (selectedKeys, info) => {
		let cid = selectedKeys[0];
		if (cid) {
			// 控制菜单一直被选中，不会再次点击取消
			this.setState({ selectedKeys: cid });
			let numbers = cid.lastIndexOf("-");
			let c = cid.slice(0, numbers);
			if (info.node._reactInternalFiber.pendingProps.info) {
				let nodeInfo = info.node._reactInternalFiber.pendingProps.info;
				if (nodeInfo.parentId === "0") {
					this.setState({ buttonDJ: true }); // 判断选中所有分类按钮是否禁用
				} else {
					this.setState({ buttonDJ: false }); // 判断选中所有分类按钮是否禁用
				};
				if (nodeInfo.disabled && nodeInfo.parentId != "0") {
					this.setState({ buttonDJ: true }); // 判断选中所有分类按钮是否禁用
				} else if (!nodeInfo.disabled && nodeInfo.parentId != "0") {
					this.setState({ buttonDJ: false });
				};
				const { disabled, parentPath, path, parentId } = info.node._reactInternalFiber.pendingProps.info;
				const { title } = info.node._reactInternalFiber.pendingProps;
				console.log(cid, title);
				this.setState({ path, parentPath, disabled, cid, title, targetRobotId: c, isShared: false, parentId });
				this.props.terrNodeId(cid, title, info.node.props.info.path, false, parentPath, parentId);
			}
		}

		// 如果该节点下又子菜单，则触发点击菜单展开收起的方法
		const nodeChildren = info.node.getNodeChildren();
		if (nodeChildren.length > 0) {
			this.onClickToCollapse(info.node.props.eventKey);
		}

		// 选中后存入local Storage
		console.log(info.node.props);
		const obj = {
			cid: info.node.props.eventKey,
			parentId: info.node.props.info.parentId,
			title: info.node.props.title,
			parentPath: info.node.props.info.parentPath,
		};
		window.localStorage.setItem("currentNode", JSON.stringify(obj));
	};

	/**
	 * 触发点击菜单展开收起的方法
	 * @param cid
	 */
	onClickToCollapse = (cid) => {
		let { expandedKeys } = this.state;
		let expandedKeysNew = [];
		if (expandedKeys.indexOf(cid) === -1) {
			expandedKeys.push(cid);
			expandedKeysNew = expandedKeys;
		} else {
			const index = expandedKeys.indexOf(cid);
			expandedKeysNew = expandedKeys.filter((item, i) => i != index);
		};
		this.doExpand(expandedKeysNew);
	};

	renderTreeNodes(data) {
		const { expandedKeys, selectedKeys } = this.state;
		// console.log(selectedKeys);
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode
						className={item.disabled ? "glo" : ""}
						title={item.name}
						key={item.id}
						info={{
							parentPath: item.parentPath,
							parentId: item.parentId,
							disabled: item.disabled,
							weight: item.weight,
						}}
						icon={expandedKeys.indexOf(item.id) === -1 ?
							<img src={staticPath + "/sysKnowledge/unfold.png"} />
							:
							<img src={staticPath + "/sysKnowledge/fold.png"} />
						}
					>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			};
			return (
				<TreeNode
					isLeaf={true}
					title={item.name}
					key={item.id}
					info={{
						parentPath: item.parentPath,
						parentId: item.parentId,
						disabled: item.disabled,
						weight: item.weight,
					}}
					icon={<img src={staticPath + "/sysKnowledge/leaf.png"} />}
					switcherIcon={<Icon type="minus-square" />}
				/>
			);
		});
	}

	move(data) {
		return data.map((item) => {
			if (item.children) {
				if (item.data.disabled) {
					return (
						<TreeNodes className='glo' value={item.text} title={item.text} key={item.id} tcx={item.data}>{this.move(item.children)}</TreeNodes>
					);
				} else {
					return (
						<TreeNodes value={item.text} title={item.text} key={item.id} tcx={item.data}>{this.move(item.children)}</TreeNodes>
					);
				}
			};
			return (
				<TreeNodes value={item.text} title={item.text} key={item.id} tcx={item.data} />
			);
		});
	}

	unfoldIcon = () => {
		// 显示
		if (this.state.isShared) {
			return message.info(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.sharedKnowledgeNotSupported' }));
		};
		this.setState({ iconJudge: false });
	};

	reference = () => {
		const { selectedKeys } = this.state;
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init({ type: 'classify', id: selectedKeys })
		}
	}

	hiddenIcon = () => {
		// 隐藏
		this.setState({ iconJudge: true });
	};

	deleteCategory = () => {
		// 删 除
		const { cid, selectedKeys } = this.state;
		const that = this;
		if (!selectedKeys || selectedKeys.length === 0) {
			return message.error(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.noNodeSelectedDelete' }));
		};
		confirm({
			title: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.confirmDeleteNode' }),
			okText: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.confirm' }),
			okType: "danger",
			cancelText: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.cancel' }),
			onOk() {
				that.deleteOk();
			},
			onCancel() { },
		});
	};

	deleteOk = () => {
		const { dispatch } = this.props;
		const { path, cid, parentPath } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "leftTree/deleteClassify",
				payload: { parentPath, id: cid },
				callback: (res) => {
					message["info"](`${res.message}`);
					//删除节点后要同步删除存储的节点
					window.localStorage.removeItem("currentNode");
					this.fetch(true);
				},
			});
		});
	};

	upOrDownCategory = (number) => {
		const { cid, dataTree, selectedKeys } = this.state;
		if (!selectedKeys || selectedKeys.length === 0) {
			return message.error(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.noNodeSelectedOperation' }));
		};
		this.queryParentNode(dataTree, cid, number);
	};

	/**
	 * 获取当前节点的数据（用于上移下移）
	 * @returns {MessageType}
	 */
	queryParentNode = (data, currentNodeId, type) => {
		for (const item of data) {
			if (currentNodeId === item.id) {
				this.queryBrotherNode(data, item, type);
			};
			if (item.children) {
				this.queryParentNode(item.children, currentNodeId, type);
			}
		}
	};

	/**
	 * 获取当前节点的兄弟节点
	 * @returns {MessageType}
	 */
	queryBrotherNode = (data, item, type) => {
		let brotherId = null;
		data.map((dataItem, index) => {
			if (dataItem.id === item.id) {
				if (type === 0 && index === 0) {
					message.error(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.nodeAlreadyFirst' }));
					return false;
				};
				if (type === 1 && index === data.length - 1) {
					message.error(formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.nodeAlreadyLast' }));
					return false;
				};
				if (type === 0) {
					// 上移
					brotherId = data[index - 1].id;
				};
				if (type === 1) {
					// 下移
					brotherId = data[index + 1].id;
				}
			}
		});
		if (brotherId) {
			this.doUpOrDown(brotherId);
		}
	};

	/**
	 * 上移下移请求接口
	 * @returns {MessageType}
	 */
	doUpOrDown = (brotherId) => {
		const { dispatch } = this.props;
		const { cid } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "leftTree/upOrDownCategory",
				payload: { id: cid, targetId: brotherId },
				callback: (res) => {
					message["info"](`${res.message}`);
					this.fetch(100);
				},
			});
		});
	};

	businessWay = () => {
		// 修改节点名
		let userInfo = this.props.form.getFieldsValue();
		this.props.form.validateFields((err, values) => {
			if (err) {
				return false;
			};
			const { dispatch } = this.props;
			const { parentPath, cid } = this.state;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "leftTree/ClassifyName",
					payload: { name: userInfo.businessName, id: cid },
					callback: (res) => {
						this.props.form.setFields({ businessName: "" });
						this.props.form.setFields({ addName: "" });
						message["info"](`${res.message}`);
						//修改节点后，要同步修改存储的节点信息
						let currentNode = JSON.parse(window.localStorage.getItem("currentNode"));
						currentNode.title = userInfo.businessName;
						window.localStorage.setItem("currentNode", JSON.stringify(currentNode));

						this.setState({ showModel: false, title: userInfo.businessName });
						this.fetch();
					},
				});
			});
		});
	};

	revisionName = () => {
		const { selectedKeys, title } = this.state;
		if (selectedKeys) {
			this.setState({ showModel: true }, () => {
				this.props.form.setFieldsValue({ businessName: title });
			});
		} else {
			message["error"](formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.noNodeSelectedRename' }));
		}
	};

	addName = () => {
		// 添加分类名 addClassify
		let userInfo = this.props.form.getFieldsValue();
		this.props.form.validateFields((err, values) => {
			if (!err) {
				let str = userInfo.addName;
				let val = str.replace(/\s*/g, "");
				let Regx = /^[A-Za-z0-9\u4e00-\u9fa5]*$/;
				if (Regx.test(val)) {
					if (val.length < 21 && val.length > 0) {
						let a = str.replace(/\s*/g, "");
						const { dispatch } = this.props;
						const { parentPath, cid, parentId } = this.state;
						this.reqRef = requestAnimationFrame(() => {
							dispatch({
								type: "leftTree/addClassify",
								payload: { name: a, parentPath: parentPath, parentId: cid },
								callback: (res) => {
									this.props.form.setFields({ addName: "" });
									message["info"](`${res.message}`);
									this.setState({ showModelA: false });
									this.fetch();
									const treeExpandedKeys = window.localStorage.getItem("treeExpandedKeys");
									if (treeExpandedKeys) {
										let expandedKeys = treeExpandedKeys.split(",");
										if (expandedKeys.indexOf(cid) === -1) {
											expandedKeys.push(cid);
										};
										window.localStorage.setItem("treeExpandedKeys", expandedKeys);
										this.setState({ expandedKeys });
									}
								},
							});
						});
					} else if (val.length === 0) { } else {
						message.error("分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败");
					}
				} else {
					message.error("分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败");
				}
			}
		});
	};

	addsName = () => {
		const { selectedKeys } = this.state;
		if (selectedKeys) {
			this.setState({ showModelA: true });
		} else {
			message["error"]("您还未选择需要添加分类的节点");
		}
	};

	checkFieldForCategoryName(rule, value, callback) {
		const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
		if (rule.field === "businessName" || rule.field === "addName") {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 20 || value.length < 0) {
						callback("支持20位以内大小写字母、数字和中文");
					} else {
						callback();
					}
				} else {
					callback("支持20位以内大小写字母、数字和中文");
				}
			} else {
				callback("支持20位以内大小写字母、数字和中文");
			}
		}
	}

	/**
	 * 分类树展开收起的回调
	 */
	doExpand = (expandedKeys, node) => {
		window.localStorage.setItem("treeExpandedKeys", expandedKeys);
		this.setState({ expandedKeys, autoExpandParent: false });
	};

	render() {
		const { iconJudge, expandedKeys, autoExpandParent, selectedKeys, rootNode } = this.state;
		const { getFieldDecorator } = this.props.form;
		const FormItemLayont = {
			labelCol: {
				xs: 24,
				sm: 5,
			},
			wrapperCol: {
				xs: 24,
				sm: 19,
			},
		};
		const buttonDJ = this.state.buttonDJ || (!UserSession.isAdmin() && UserSession.isSystemKnowledge())
			? { pointerEvents: "none", opacity: "0.5" }
			: null;
		const buttonNonew = this.state.buttonNonew || (!UserSession.isAdmin() && UserSession.isSystemKnowledge())
			? { pointerEvents: "none", opacity: "0.5" }
			: null;
		const { authority } = this.props;

		return (
			<div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
				<div className={styles.topBar}>
					{iconJudge === true ? (
						<div>
							<span style={{ paddingTop: 2, fontWeight: 600 }}>{formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.knowledgeClassification' })}</span>
							{UserSession.isSystemKnowledge() ? rootNode === selectedKeys ? null : (
								<div onClick={this.reference} style={{ float: "right", cursor: "pointer", paddingBottom: 9, fontSize: 16 }}>
									<Icon type="block" style={{ paddingBottom: 5 }} />
								</div>
							) : (
								<>
									{!this.state.isShared && authority === 2 ? (
										<div onClick={this.unfoldIcon} style={{ float: "right", cursor: "pointer", paddingBottom: 9, fontSize: 16 }}>
											<img style={{ paddingBottom: 5 }} src={jin} />
										</div>
									) : ("")}
								</>
							)}
						</div>
					) : (
						<div className={styles.bj}>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.moveUp' })} arrowPointAtCenter>
								<img
									src={icon1}
									style={rootNode === selectedKeys ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
									onClick={() => this.upOrDownCategory(0)}
									className={styles.iconsNew}
								/>
							</Tooltip>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.moveDown' })} arrowPointAtCenter>
								<img
									src={icon2}
									style={rootNode === selectedKeys ? { pointerEvents: "none", opacity: "0.5" } : buttonDJ}
									onClick={() => this.upOrDownCategory(1)}
									className={styles.iconsNew}
								/>
							</Tooltip>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.deleteCategory' })} arrowPointAtCenter>
								<img
									src={icon4}
									style={
										rootNode === selectedKeys ||
											(!UserSession.isAdmin() && UserSession.isSystemKnowledge())
											? { pointerEvents: "none", opacity: "0.5" }
											: buttonDJ
									}
									className={styles.iconsNew}
									onClick={this.deleteCategory}
								/>
							</Tooltip>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.renameCategory' })} arrowPointAtCenter>
								<img
									style={
										rootNode === selectedKeys ||
											(!UserSession.isAdmin() && UserSession.isSystemKnowledge())
											? { pointerEvents: "none", opacity: "0.5" }
											: buttonDJ
									}
									onClick={this.revisionName}
									className={styles.iconsNew}
									src={icon6}
								/>
							</Tooltip>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addCategory' })} arrowPointAtCenter>
								<img style={buttonNonew} onClick={this.addsName} className={styles.iconsNew} src={icon7} />
							</Tooltip>
							<Tooltip placement='top' title={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.return' })} arrowPointAtCenter>
								<img onClick={this.hiddenIcon} className={styles.iconsNew} src={chu} style={{ height: 14, marginTop: 3 }} />
							</Tooltip>
						</div>
					)}
				</div>
				<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
				<Spin className={styles.spin} spinning={this.state.loading}>
					{this.state.dataTree.length === 0 ? null : (
						<DirectoryTree
							onSelect={this.onSelect}
							expandedKeys={expandedKeys}
							onExpand={this.doExpand}
							showIcon={true}
							autoExpandParent={autoExpandParent}
							selectedKeys={[selectedKeys]}
							showLine={true}
							className="knowledgeTree"
						>
							{this.renderTreeNodes(this.state.dataTree)}
						</DirectoryTree>
					)}
				</Spin>
				<Modal
					className='modelZdy'
					title='修改节点名称'
					visible={this.state.showModel}
					okText={<FormattedMessage id='app.customDictionary.save' />}
					cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
					onCancel={() => {
						this.props.form.setFields({ businessName: "" });
						this.setState({ showModel: false });
					}}
					onOk={this.businessWay}
					destroyOnClose
				>
					<Form layout='horizontal'>
						<FormItem label='新节点名' {...FormItemLayont}>
							{getFieldDecorator("businessName", {
								rules: [
									{ required: this.state.showModel, message: "节点名不能为空" },
									{ validator: this.state.showModel ? this.checkFieldForCategoryName : "", },
								],
							})(<Input onPressEnter={this.businessWay} />)}
						</FormItem>
					</Form>
				</Modal>
				<Modal
					className='modelZdy'
					title='添加分类'
					visible={this.state.showModelA}
					okText={<FormattedMessage id='app.customDictionary.save' />}
					cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
					onCancel={() => {
						this.props.form.setFields({ addName: "" });
						this.setState({ showModelA: false });
					}}
					onOk={this.addName}
					destroyOnClose
				>
					<Form layout='horizontal'>
						<FormItem label='添加分类名' {...FormItemLayont}>
							{getFieldDecorator("addName", {
								initialValue: "",
								rules: [
									{ required: this.state.showModelA, message: "分类名不能为空", },
									{ validator: this.state.showModelA ? this.checkFieldForCategoryName : "", },
								],
							})(<Input onPressEnter={this.addName} />)}
						</FormItem>
					</Form>
				</Modal>
			</div>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(LeftTree));
